import { Message, Notification } from 'element-ui';
import BudgetBaseInfo from './BudgetBaseInfo/BudgetBaseInfo.vue';
import BudgetTemplate from './BudgetTemplate/BudgetTemplate.vue';
import BudgetSupplement from './BudgetSupplement/BudgetSupplement.vue';

export default {
    name: 'SelectProjectBudget',
    props: ['data'],
    components: {
        BudgetBaseInfo,
        BudgetTemplate,
        BudgetSupplement
    },
    data() {
        return {
            isAdd: false,
            show: false,
            importUrl: '/api/budget/import',
            activeNames: [0, 1, 2],
            submitImportFlg: '',
            uploadBtnDisabled: {
                budgetDetailTemplate: false,
                budgetDetailCustom: false
            }
        };
    },
    computed: {
        collapseConfig() {
            return [
                {
                    label: '工单基本信息',
                    comp: 'BudgetBaseInfo'
                },
                {
                    label: '模板项',
                    btnId: 'budgetDetailTemplate',
                    comp: 'BudgetTemplate'
                },
                {
                    label: '补充项',
                    btnId: 'budgetDetailCustom',
                    comp: 'BudgetSupplement'
                }
            ];
        },
        detailBtns() {
            return [
                { label: '取消', type: '', click: this.cancel },
                { label: '保存', type: 'primary', click: this.save },
                { label: '提交', type: 'primary', click: this.submit }
            ];
        }
    },
    methods: {
        handleClose() {
            this.$emit('update:show', false);
            this.data.budgetDetailTemplate = [];
            this.data.budgetDetailCustom = [];
            this.data.designFiles = '';
            this.isAdd = false;
            this.$parent.isModify = false;
        },

        showDialog() {
            this.show = true;
        },
        importTemp(btnId) {
            // 1模板项 2补充项//初始化导入提交
            this.submitImportFlg = btnId;
            const importBtn = document.getElementById(btnId);
            let excelPath = importBtn.value;

            console.info('名称' + excelPath);
            if (excelPath == null || excelPath === '') {
                Message({
                    message: '请选择要上传的Excel文件！',
                    type: 'warning'
                });
                document.getElementById(btnId).value = '';
                this.submitImportFlg = '';
            } else {
                let fileExtend = excelPath.substring(excelPath.lastIndexOf('.')).toLowerCase();
                if (fileExtend !== '.xls' && fileExtend !== '.xlsx') {
                    Message({
                        message: '文件格式需为.xls或者.xlsx格式！',
                        type: 'warning'
                    });
                    this.submitImportFlg = '';
                    importBtn.value = '';
                    return;
                }

                let files = importBtn.files;
                let fd = new FormData();
                fd.append('excelFile', files[0]);
                this.$httpExt()
                    .post(
                        this.importUrl,
                        fd,
                        { emulateHTTP: true },
                        {
                            headers: { 'Content-Type': 'multipart/form-data' }
                        }
                    )
                    .then(response => {
                        if (response.code === '200') {
                            Notification.success({
                                title: '成功',
                                message: '导入成功'
                            });
                            this.importDialog = false;
                            this.submitImportFlg = '';
                            this.data[btnId] = response.data;
                            importBtn.value = '';
                            this.uploadBtnDisabled[btnId] = true;
                        } else {
                            this.submitImportFlg = '';
                            this.showErrorFlg = true;
                        }
                    });
            }
        },
        down(type) {
            // 模板项需要下载项目数据
            if (type === 'budgetDetailTemplate') {
                let yearBudgetNumber;
                const { currentOrderRow } = this.$parent;
                if (this.isAdd) {
                    yearBudgetNumber = currentOrderRow.yearBudgetNumber;
                } else {
                    yearBudgetNumber = this.data.yearBudgetNumber;
                }

                location.href = `/api/budget/export/${yearBudgetNumber}?token=${sessionStorage.getItem('token')}`;
            } else {
                location.href = `/api/common/downloadTemplate?templateType=${type}&token=${sessionStorage.getItem(
                    'token'
                )}`;
            }
        },
        cancel() {
            this.show = false;
        },
        getParams() {
            const ret = {};
            const formFields = [
                'constructionProjectName',
                'constructionProjectAddress',
                'constructionProjectArea',
                'constructionType',
                'id',
                'invoiceTaxRate',
                'workOrderNumber',
                'supplierCode',
                'orderDept',
                'budgetType',
                'designFiles',
                'projectBudget',
                'amountExcludingTax'
            ];
            // 标识是否为新增
            const { currentOrderRow } = this.$parent;
            if (this.isAdd) {
                // 新增时一部分数据从接口获取，一部分从表单获取
                formFields.forEach(v => (ret[v] = this.data[v]));
                ret.workOrderNumber = currentOrderRow.orderNo;
                ret.orderDept = currentOrderRow.orderDept;
                ret.id = ''; // 新增时不需要id
            } else {
                formFields.forEach(v => (ret[v] = this.data[v]));
            }

            const { budgetDetailTemplate = [], budgetDetailCustom = [] } = this.data;

            budgetDetailTemplate.forEach(v => (v.detailType = '1'));
            budgetDetailCustom.forEach(v => (v.detailType = '2'));

            ret.cbdList = budgetDetailTemplate.concat(budgetDetailCustom);
            return ret;
        },
        async saveOrSubmit(opt) {
            let res;
            res = await this.$httpExt().post('/api/budget/saveOrUpdate', {
                opt,
                ...this.getParams()
            });
            if (res && res.code === '200') {
                Message({
                    type: 'success',
                    message: opt === 'save' ? '保存成功' : '提交成功'
                });
                this.show = false;
                this.$parent.showProjectBudget = false;
            }
        },
        async save() {
            this.saveOrSubmit('save');
        },
        submit() {
            this.saveOrSubmit('submit');
        }
    },
    mounted() {
        this.$root.$on('uploadBtnDisabled', (key, value) => {
            this.uploadBtnDisabled[key] = value;
        });
    }
};
